﻿using System;
using System.Web;
using System.Web.Security;

namespace Facebook.Web.Security
{
    public class FacebookAuthenticationModule : IHttpModule
    {
        #region [ IHttpModule Members ]

        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(Object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;
            HttpContext context = application.Context;
            if (!FacebookWebContext.IsReady(context))
            {
                FacebookWebContext.Init(context);
            }

            if (this.FbContext.HasSession)
            {
                // Note: For FBML applications, this will only effectively last for the duration of the request.
                FormsAuthentication.SetAuthCookie(this.FbContext.Session.Uid.ToString(), this.FbContext.Session.Expires == DateTime.MaxValue);                
            }
        }

        #endregion

        private FacebookWebContext FbContext
        {
            get { return FacebookWebContext.Current; }
        }
    }
}